package com.simplenix.nicasio.hmaint;

import com.simplenix.nicasio.sys.SystemDef;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.hibernate.util.XMLHelper;

/**
 *
 * @author fronald
 */
public class EntityFactory {

	private Map<String, EntityDefinition> ed;

	private static EntityFactory ef;

	private Logger log = Logger.getLogger(getClass().getName());

	public static EntityFactory getInstance() throws HMaintException {
		if (ef == null) {
			ef = new EntityFactory();
		}
		return ef;
	}

	private EntityFactory() throws HMaintException {
		this.ed = new HashMap();
		try {
			List<String> errors = new ArrayList<String>();
			XMLHelper x = new XMLHelper();
			Document configHibernate = x.createSAXReader(SystemDef.getInstance().getAppPath() + "/WEB-INF/classes/hibernate.cfg.xml", errors, XMLHelper.DEFAULT_DTD_RESOLVER).read(new File(SystemDef.getInstance().getAppPath() + "/WEB-INF/classes/hibernate.cfg.xml"));
			Element root = configHibernate.getRootElement();
			Element sessionFactory = root.element("session-factory");
			List<Element> mappings = sessionFactory.elements("mapping");
			for (Element mapping : mappings) {
				String className = mapping.attributeValue("class");
				if (EntityDefinition.isValidHMaintEntity(className)) {
					EntityDefinition def = new EntityDefinition(className);
					this.ed.put(className, def);
					this.log.info("Entity class " + className + " loaded.");
				}
			}
		} catch (DocumentException ex) {
			throw new HMaintException(ex);
		}
	}

	public EntityDefinition getEntityDefinition(Class entityClass) {
		return this.getEntityDefinition(entityClass.getName());
	}

	public EntityDefinition getEntityDefinition(String entityClassName) {
		return this.ed.get(entityClassName);
	}

}
